/**
 * Copyright &copy; 2016-2017 <a href="http://git.oschina.net/whoamien/backend_management">Backend Management</a> All rights reserved.
 */
package com.xw.app.controller;

import java.util.Arrays;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.xw.app.model.AcctUser;
import com.xw.app.model.AcctUser;
import com.xw.app.model.AcctUser;
import com.xw.app.service.AcctUserService;
import com.xw.app.service.SysDictService;
import com.xw.app.service.SystemConfigService;
import com.xw.app.vo.query.AcctUserQuery;
import com.xw.framework.base.controller.BaseSpringController;
import com.xw.framework.encryption.MD5Util;
import com.xw.util.BeanUtils;

/**
 * The Class AcctUserController.
 *
 * @author Xi Wei
 */
@Controller
@RequestMapping("/acctUser")
public class AcctUserController extends BaseSpringController {

	@Autowired
	private AcctUserService acctUserService;
	
	@Autowired
	private SysDictService sysDictService;
	@Autowired
	private ImageUpload imageUpload;
	@Autowired
	private SystemConfigService systemConfigService;
	
	/**
	 * List.
	 *
	 * @param request the request
	 * @param query the query
	 * @return the model and view
	 */
	@RequestMapping("/list")
	public ModelAndView list(HttpServletRequest request,AcctUserQuery query){
		Page<AcctUser> page = acctUserService.findPage(query);
		request.getSession().setAttribute(AcctUserQuery.class.getSimpleName(), query);
		ModelAndView result = new ModelAndView("/AcctUser/list");
		ModelMap map = toModelMap(page, query);
		map.addAttribute("genderMap", sysDictService.getDictMapByCode("GENDER"));
		map.addAttribute("systemMap",systemConfigService.getSystemMap());
		result.addAllObjects(map);
		return result;		
	}
	
	/**
	 * Creates the.
	 *
	 * @param acctUser the acct user
	 * @return the model and view
	 */
	@RequestMapping("/popup/create")
	public ModelAndView create(AcctUser acctUser){
		ModelAndView result = new ModelAndView("/AcctUser/add");
		ModelMap map = new ModelMap();
		map.addAttribute("genderMap", sysDictService.getDictIntegerMapByCode("GENDER"));
		map.addAttribute("systemMap",systemConfigService.getSystemMap());
		if(acctUser.getId() != null){
			acctUser = acctUserService.getById(acctUser.getId());
		}
		map.addAttribute("acctUser", acctUser);
		result.addAllObjects(map);
		return result;
	}
	
	/**
	 * Save.
	 *
	 * @param acctUser the acct user
	 * @param validateResult the validate result
	 * @param request the request
	 * @param redirectAttributes the redirect attributes
	 * @return the model and view
	 */
	@RequestMapping("/popup/save")
	public ModelAndView save(@Valid AcctUser acctUser,BindingResult validateResult,
			HttpServletRequest request,RedirectAttributes redirectAttributes){
		if(validateResult.hasErrors()){
			return create(acctUser);
		}
		
		acctUser.setPassword(MD5Util.pwdEncrypt(acctUser.getPassword()));
		if(acctUser.getId() != null){
			AcctUser existing = acctUserService.getById(acctUser.getId());
			BeanUtils.copyProperties(existing, acctUser);
			acctUserService.save(existing);
		}else{
			acctUserService.save(acctUser);
		}
		
		ModelMap map = new ModelMap();
		ModelAndView result = new ModelAndView("/saveResult");
		map.addAttribute("msg", "success");
		result.addAllObjects(map);
		addMessage(redirectAttributes, "添加成功");
		return result;
	}
	
	/**
	 * Profile.
	 *
	 * @param acctUser the acct user
	 * @param session the session
	 * @return the model and view
	 */
	@RequestMapping("/profile")
	public ModelAndView profile(AcctUser acctUser,HttpSession session){
		if(acctUser == null || acctUser.getId() == null){
			acctUser = getUserSessionInfo(session).getAcctUser();
		}
		ModelAndView result = new ModelAndView("/AcctUser/profile");
		ModelMap map = new ModelMap();
		map.addAttribute("acctUser", acctUser);
		map.addAttribute("systemMap",systemConfigService.getSystemMap());
		map.addAttribute("genderMap", sysDictService.getDictIntegerMapByCode("GENDER"));
		result.addAllObjects(map);
		return result;
	}
	
	/**
	 * Save profile.
	 *
	 * @param acctUser the acct user
	 * @param validationResult the validation result
	 * @param request the request
	 * @param redirectAttributes the redirect attributes
	 * @param file the file
	 * @return the model and view
	 * @throws Exception the exception
	 */
	@RequestMapping("/saveProfile")
	public ModelAndView saveProfile(@Valid AcctUser acctUser,BindingResult validationResult, 
			HttpServletRequest request,RedirectAttributes redirectAttributes,
			@RequestParam(value = "file", required = false) MultipartFile file) throws Exception{
		if(validationResult.hasErrors()){
			return profile(acctUser,request.getSession());
		}
		AcctUser existing = acctUserService.getById(acctUser.getId());
		existing.setGender(acctUser.getGender());
		existing.setHomePhone(acctUser.getHomePhone());
		existing.setWorkPhone(acctUser.getWorkPhone());
		existing.setMobilePhone(acctUser.getMobilePhone());
		existing.setUserName(acctUser.getUserName());
		if(file != null){
			String path = imageUpload.uploadImage(request, file, "upload/avatar");
			existing.setLogo(path);
		}
		acctUserService.save(existing);
		getUserSessionInfo(request.getSession()).setAcctUser(existing);
		addMessage(redirectAttributes, "个人资料保存成功");
		return new ModelAndView("redirect:/acctUser/profile");
	}
	
	
	/**
	 * Delete.
	 *
	 * @param id the id
	 * @return the string
	 */
	@RequestMapping("/json/delete")
	@ResponseBody
	public String delete(Long id){
		acctUserService.delete(id);
		return "success";
		
	}
	
	/**
	 * Delete all.
	 *
	 * @param ids the ids
	 * @return the string
	 */
	@RequestMapping("/json/deleteAll")
	@ResponseBody
	public String deleteAll(String ids){
		System.out.println(ids);
		if(ids != null && ids.trim().length() > 0){
			Arrays.asList(ids.split(",")).forEach(x -> acctUserService.delete(Long.valueOf(x)));
		}
		return "success";
	}
	
	/**
	 * Check user exist.
	 *
	 * @param loginName the login name
	 * @return the boolean
	 */
	@RequestMapping("/json/checkUserExist")
	@ResponseBody
	public Boolean checkUserExist(String loginName){
		AcctUser acctUser = acctUserService.getUserByLoginName(loginName);
		if(acctUser == null){
			return true;
		}
		return false;
	}
}
